package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

// 升级器，用于将 HTTP 连接升级为 WebSocket 连接
var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	// 允许所有来源，避免跨域问题
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func wsHandler(w http.ResponseWriter, r *http.Request) {
	// 将 HTTP 连接升级为 WebSocket 连接
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("升级为 WebSocket 连接失败:", err)
		return
	}
	defer conn.Close()

	log.Println("WebSocket 客户端已连接")

	// 监听来自客户端的消息
	for {
		// 读取客户端消息
		messageType, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("读取消息时发生错误:", err)
			break
		}

		// 打印收到的消息
		fmt.Printf("收到消息: %s\n", message)

		// 发送回客户端
		responseMessage := fmt.Sprintf("服务端收到: %s", message)
		err = conn.WriteMessage(messageType, []byte(responseMessage))
		if err != nil {
			log.Println("发送消息时发生错误:", err)
			break
		}
	}
}

func main() {
	http.HandleFunc("/hmi/tedge/tagbook", wsHandler)

	// 启动 WebSocket 服务器，监听端口 30000
	log.Println("WebSocket 服务器已启动，监听端口 30000")
	err := http.ListenAndServe(":30000", nil)
	if err != nil {
		log.Fatal("服务器启动失败:", err)
	}
}
